﻿using Demo.Net.Infrastructure;
using Demo.Net.SqlSugar;
using IdentityServer4.Models;
using IdentityServer4.Validation;
using System.Drawing.Drawing2D;
using System.Security.Claims;


namespace Demo.Net.IdentityServer.IdentityServer
{
    /// <summary>
    /// 帐号密码登录
    /// </summary>
    public class ApLoginGrantValidator : IExtensionGrantValidator
    {
        /// <summary>
        /// 自定义用户授权类型
        /// </summary>
        public string GrantType
        {
            get
            {
                return GrantTypeConst.ApLoginGrant;
            }
        }

        private readonly SqlSugarDBCom _dbCom;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="microService"></param>
        public ApLoginGrantValidator(IServiceProvider serviceProvider)
        {

            _dbCom = serviceProvider.GetRequiredService<SqlSugarDBCom>();
        }

        /// <summary>
        /// 授权认证
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task ValidateAsync(ExtensionGrantValidationContext context)
        {
            try
            {
                await Task.Yield();
                var user_name = context.Request.Raw["user_name"];  // 帐号
                var user_pwd = context.Request.Raw["user_pwd"];  // 密码
                if (string.IsNullOrWhiteSpace(user_name))
                {
                    context.Result = new GrantValidationResult
                    (
                        error: TokenRequestErrors.InvalidGrant,
                        errorDescription: "帐号不能为空"
                    );
                    return;
                }
                if (string.IsNullOrWhiteSpace(user_pwd))
                {
                    context.Result = new GrantValidationResult
                    (
                        error: TokenRequestErrors.InvalidGrant,
                        errorDescription: "密码不能为空"
                    );
                    return;
                }

                // 获取用户基本信息
                var user = await _dbCom.Tusr_User.AsQueryable().SingleAsync(p => p.UserName == user_name);
                if (user == null)
                {
                    context.Result = new GrantValidationResult
                    (
                        error: TokenRequestErrors.InvalidGrant,
                        errorDescription: "帐号不存在"
                    );
                    return;
                }
                var pwd = SecurityHelper.MD5WithSalt(user_pwd, user.PwdSalt);
                if (pwd != user.UserPwd)
                {
                    context.Result = new GrantValidationResult
                    (
                        error: TokenRequestErrors.InvalidGrant,
                        errorDescription: "密码错误"

                    );
                    return;
                }
                //这些Claim声明如果需要包含在最终颁发的令牌中，需要配置 ProfileService
                var claims = new List<Claim>
                {
                  new Claim(ClaimTypes.NameIdentifier, user.UserId.ToString()),
                  new Claim(ClaimTypes.Name, user.UserName),
                  new Claim("realname",user.RealName)
                };

                context.Result = new GrantValidationResult(
                    subject: user.UserId.ToString(),
                    authenticationMethod: GrantType,
                    claims: claims
                );

            }
            catch (Exception ex)
            {
                context.Result = new GrantValidationResult
                (
                    error: TokenRequestErrors.InvalidGrant,
                    errorDescription: ex.Message
                );
            }
        }
    }
}
